<template>
  <div class="analysis2-container">
    <div class="left-container">
      <div
        class="left-item"
        :class="leftIndex === index && 'active'"
        v-for="(item, index) in leftData"
        :key="index"
        @click="leftClick(index, item)"
      >{{ item.name }}</div>
    </div>
    <div class="right-container">
      <div class="query-container">
        <el-select
          v-model="queryType"
          placeholder="请选择"
          style="margin-right: 30px;"
          @change="queryModel = null"
        >
          <el-option v-for="item in queryTypes" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <el-date-picker
          v-if="queryType === '年'"
          v-model="queryModel"
          align="right"
          type="year"
          value-format="yyyy"
          :clearable="false"
          placeholder="选择年份"
        ></el-date-picker>
        <el-date-picker
          v-if="queryType === '月'"
          v-model="queryModel"
          align="right"
          type="month"
          value-format="yyyy-MM"
          :clearable="false"
          placeholder="选择月份"
        ></el-date-picker>
        <el-date-picker
          v-if="queryType === '日'"
          v-model="queryModel"
          align="right"
          type="date"
          value-format="yyyy-MM-dd"
          :clearable="false"
          placeholder="选择日期"
        ></el-date-picker>
        <el-button type="primary" style="margin-left: 30px;" @click="getTopData">查询</el-button>
      </div>
      <div class="top-chart" ref="topChart"></div>
      <div class="bottom-chart" ref="bottomChart"></div>
    </div>
  </div>
</template>

<script>
import echarts from "echarts";
import moment from "moment";

export default {
  data() {
    return {
      queryTypes: ["年", "月", "日"],
      queryType: "年",
      queryModel: moment().format("YYYY"),
      leftData: [],
      leftIndex: 0,
      topChart: null,
      bottomChart: null,
      date: null, // null 初始 1 年 2月 3日
      type: null, // 冷：COOLINGLOAD 热：HEATLOAD  电：ELECTRICLOAD
      typ1: null,
      code: null
    };
  },
  async mounted() {
    await this.getLeftData();
    this.code = this.leftData[this.leftIndex].code
    await this.getTopData();
  },
  methods: {
    async getLeftData() {
      const result = await this.$fetchGet("/common/findAllPowerEnum");
      this.leftData = result.result.userPower;
    },
    async getTopData(type) {
      const year = moment().format("YYYY");
      if (!this.queryModel) {
        this.$message.warning('请先选择时间')
        return
      }
      let timeType
      if (this.queryType === '年') {
        timeType = 'YEAR'
      } else if (this.queryType === '月') {
        timeType = 'MONTH'
      } else {
        timeType = 'DAY'
      }
      let arr = this.queryModel.split('-')
      let title
      if (arr.length === 1) {
        title = arr[0] + '年'
      } else if (arr.length === 2){
        title = arr[0] + '年' + arr[1] + '月'
      } else {
        title = arr[0] + '年' + arr[1] + '月' + arr[2] + '日'
      }
      const result = await this.$fetchGet(
        `/power/getUserPowerDtoByPowerType/${timeType}/${this.queryModel}/${this.code}`
      );
      if (this.topChart) {
        this.topChart.setOption(
          this.topOption(
            `${title}${this.leftData[this.leftIndex].name}能源占比`,
            [
              {
                name: "电",
                value: !result.result.length ? 0 : result.result[0].electricLoad
              },
              {
                name: "冷",
                value: !result.result.length ? 0 : result.result[0].coolingLoad
              },
              {
                name: "热",
                value: !result.result.length ? 0 : result.result[0].heatLoad
              }
            ]
          ),
          true
        );
        this.bottomChart = echarts.init(this.$refs["bottomChart"]);
        this.bottomChart.setOption(
          this.bottomOption(
            `${title}${this.leftData[this.leftIndex].name}能源使用情况`,
            [
              {
                name: "电",
                value: !result.result.length ? 0 : result.result[0].electricLoad
              },
              {
                name: "冷",
                value: !result.result.length ? 0 : result.result[0].coolingLoad
              },
              {
                name: "热",
                value: !result.result.length ? 0 : result.result[0].heatLoad
              }
            ]
          )
        );
        this.bottomChart.on("click", params => {
          this.getBottomData(params.name);
        });
      } else {
        this.topChart = echarts.init(this.$refs["topChart"]);
        this.topChart.setOption(
          this.topOption(
            `${title}${this.leftData[this.leftIndex].name}能源占比`,
            [
              {
                name: "电",
                value: !result.result.length ? 0 : result.result[0].electricLoad
              },
              {
                name: "冷",
                value: !result.result.length ? 0 : result.result[0].coolingLoad
              },
              {
                name: "热",
                value: !result.result.length ? 0 : result.result[0].heatLoad
              }
            ]
          )
        );
        this.bottomChart = echarts.init(this.$refs["bottomChart"]);
        this.bottomChart.setOption(
          this.bottomOption(
            `${title}${this.leftData[this.leftIndex].name}能源使用情况`,
            [
              {
                name: "电",
                value: !result.result.length ? 0 : result.result[0].electricLoad
              },
              {
                name: "冷",
                value: !result.result.length ? 0 : result.result[0].coolingLoad
              },
              {
                name: "热",
                value: !result.result.length ? 0 : result.result[0].heatLoad
              }
            ]
          )
        );
        this.bottomChart.on("click", () => {});
        this.bottomChart.on("click", params => {
          this.getBottomData(params.name);
        });
      }
    },
    async getBottomData(type) {
      const arr = ["电", "冷", "热"];
      const arrCode = {
        电: "ELECTRICLOAD",
        冷: "COOLINGLOAD",
        热: "HEATLOAD"
      };
      const arrCode1 = {
        电: "electricLoad",
        冷: "coolingLoad",
        热: "heatLoad"
      };
      if (arr.includes(type)) {
        this.date = moment().format("YYYY");
        this.type = arrCode[type];
        this.typ1 = arrCode1[type];
        const result = await this.$fetchGet(
          `/power/getUserPowerDtoByPowerTypeAndDate/MONTH/${this.date}/${
            arrCode[type]
          }/${this.leftData[this.leftIndex].code}`
        );
        this.bottomChart.setOption(
          this.bottomOption(
            `2020年${this.leftData[this.leftIndex].name}能源使用情况`,
            result.result.map(item => {
              return {
                name: item.createTimeU,
                value: item[this.typ1]
              };
            })
          )
        );
        // this.bottomChart.on("click", params => {
        //   this.getBottomData(params.name);
        // });
      } else {
        const arr1 = type.split("-");
        if (arr1.length === 2) {
          this.date = moment(type).format("YYYY-MM");
        } else if (arr1.length === 3) {
          this.date = moment(type).format("YYYY-MM-DD");
        }
        if (type.split(" ").length === 2) {
          this.$message.warning("最小为小时力度");
          return;
        }
        const result = await this.$fetchGet(
          `/power/getUserPowerDtoByPowerTypeAndDate/${
            arr1.length === 2 ? "DAY" : "HOUR"
          }/${this.date}/${this.type}/${this.leftData[this.leftIndex].code}`
        );
        this.bottomChart.setOption(
          this.bottomOption(
            `2020年${this.leftData[this.leftIndex].name}能源使用情况`,
            result.result.map(item => {
              return {
                name: item.createTimeU,
                value: item[this.typ1]
              };
            })
          )
        );
        // this.bottomChart.on("click", params => {
        //   this.getBottomData(params.name);
        // });
      }
    },
    leftClick(index, item) {
      this.leftIndex = index;
      this.date = null;
      this.type = null;
      this.type1 = null;
      this.topChart = null;
      // this.bottomChart = null
      this.bottomChart.dispose();
      this.code = item.code
      this.getTopData(item.code);
    },
    topOption(name, data) {
      return {
        title: {
          text: name,
          left: "center",
          top: 20
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          right: 10,
          top: 20,
          bottom: 20
        },
        color: ["#2994DF", "#9252B0", "#C79D43", "#24B9D2"],
        series: [
          {
            name: name,
            type: "pie",
            radius: "55%",
            center: ["50%", "50%"],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            },
            data: data.map(item => {
              return {
                value: item.value / 1000,
                name: item.name
              };
            })
          }
        ]
      };
    },
    bottomOption(name, data) {
      return {
        title: {
          text: name,
          left: "left",
          top: 20
        },
        color: ["#3398DB"],
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            data: data.map(item => item.name),
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: "value"
          }
        ],
        series: [
          {
            type: "bar",
            name: name,
            barWidth: "60%",
            data: data.map(item => item.value / 1000)
          }
        ]
      };
    }
  }
};
</script>

<style lang="less">
.analysis2-container {
  display: flex;
  height: calc(100vh - 60px);
  .left-container {
    width: 350px;
    overflow-y: auto;
    padding: 20px;
    .left-item {
      cursor: pointer;
      font-size: 20px;
      padding: 20px;
      border-bottom: 1px solid #888;
      &.active {
        color: #f00;
      }
    }
  }
  .right-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .query-container {
      margin-top: 20px;
      padding: 0 30px;
      text-align: right;
    }
    .top-chart {
      flex: 1;
      margin: 25px;
      border: 2px solid #efefef;
      box-sizing: border-box;
    }
    .bottom-chart {
      flex: 1;
      margin: 25px;
      border: 2px solid #efefef;
      box-sizing: border-box;
    }
  }
}
</style>